//
//  KLMAIModeController.swift
//  KLM_GN
//
//  Created by Nic on 2025/3/5.
//

import UIKit

private let cellId = String(describing: KLMAIModeCell.self)

class KLMAIModeController: KLMBaseController {
    
    @IBOutlet weak var tipLabel: UILabel!
    @IBOutlet weak var collectionView: KLMBaseCollectionView!
    @IBOutlet weak var confirmBtn: KLMCommonButton!
    
    var lastSelectIndex: IndexPath?
    var configBlcok: ConfirmConfigBlock?
    
    var modes = [KLMCard]()
    var rkScenes = [KLMRKScene]()
    
    var device: KLMHomeDevice
    var deviceConfig: KLMRKDeviceConfig
    
    init(device: KLMHomeDevice, deviceConfig: KLMRKDeviceConfig) {
        self.device = device
        self.deviceConfig = deviceConfig
        super.init(nibName: "KLMAIModeController", bundle: nil)
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loadRKSceneList()
    }
    
    // MARK: - 请求AI模式列表roomCode：line_lamp
    func loadRKSceneList() {
        SVProgressHUD.show()
        KLMRequest.queryRKDeviceSceneList(meshId: device.meshId, uuid: device.uuid, roomCode: "line_lamp") { response in
            SVProgressHUD.dismiss()
            if let list = response as? [KLMRKScene] {
                self.rkScenes = list
                self.modes = KLMCard.aiSceneModeCards(rkScenes: list)
                self.collectionView.reloadData()
            }
        } failure: { error in
            SVProgressHUD.dismiss()
            KLMHttpShowError(error)
        }
    }
    // MARK: - 确定按钮事件
    @IBAction func tapConfirmBtn(_ sender: KLMCommonButton) {
        guard let _ = modes.first(where: { $0.isOn }) else {
            return
        }
        var buttonList = [[String: Any]]()
        for (index, item) in modes.enumerated() {
            if index < rkScenes.count {
                buttonList.append([
                    "sceneCode": rkScenes[index].sceneCode ?? "",
                    "sceneButton": item.isOn ? 1 : 0
                ])
            }
        }
        if buttonList.count > 0 {
            SVProgressHUD.show()
            KLMRequest.updateRKSceneButton(meshId: device.meshId, uuid: device.uuid, sceneButtonList: buttonList) { response in
                SVProgressHUD.showSuccess(withStatus: KLMLocalizable.LANGLOC("Success"))
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    if let configBlcok = self.configBlcok {
                        configBlcok()
                    }
                    self.navigationController?.popViewController(animated: true)
                }
            } failure: { error in
                SVProgressHUD.dismiss()
                KLMHttpShowError(error)
            }
        }
    }
    override func viewDidLoadConfig() {
        super.viewDidLoadConfig()
        tipLabel.configStyle(with: "快速选择", font: UIFont(safeName: "PingFangHK-Semibold", size: 18), titleColor: rgba(38, 38, 38, 1))
        confirmBtn.configStyle(with: "确定")
        confirmBtn.updateStyle(state: .normal, cornerRadius: confirmBtn.height*0.5)
//        confirmBtn.isEnabled = false
        
        if let collectionView = collectionView {
            let layout = KLMCustomFlowLayout()
            layout.cellCountPerRow = 1
            layout.itemSize = CGSizeMake(300, 77)
            collectionView.collectionViewLayout = layout
            
            collectionView.register(UINib(nibName: cellId, bundle: nil), forCellWithReuseIdentifier: cellId)
            collectionView.delegate = self
            collectionView.dataSource = self
        }
    }

    
}
extension KLMAIModeController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return modes.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = KLMAIModeCell.cell(with: collectionView, at: indexPath, cellId: cellId)
        cell.cellCard = modes[indexPath.item]
        cell.updateIcon(rkScene: rkScenes[indexPath.item])
        cell.delegate = self
        return cell
    }
}

extension KLMAIModeController: UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let mode = modes[indexPath.item]
        let settingVc = KLMBaseModeSettingController(type: .AI, rkScene: rkScenes[indexPath.item])
        settingVc.titleText = "\(titleText ?? "AI模式")-\(mode.title)设置"
        settingVc.configBlcok = { [weak self] in
            guard let self = self else { return }
            self.loadRKSceneList()
        }
        navigationController?.pushViewController(settingVc, animated: true)
    }
}

extension KLMAIModeController: KLMAIModeCellDelegate {
    func aiModeCellToggleOn(cell: KLMAIModeCell, index: IndexPath) {
        modes[index.item].isOn = !modes[index.item].isOn
//        modes[index.item].select = !modes[index.item].select
        collectionView.reloadItems(at: [index])
        
//        guard let _ = modes.first(where: { $0.isOn }) else {
//            confirmBtn.isEnabled = false
//            return
//        }
//        confirmBtn.isEnabled = true
    }
}
    
